import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
import store from './store'
import locale from 'element-plus/dist/locale/zh-cn'
import * as echarts from 'echarts'

import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'

import * as ElementPlusIconsVue from '@element-plus/icons-vue'


import { useUserStore } from '@/store/useUserstore'

// 创建 Vue 应用
const app = createApp(App)

for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
}

// 创建 Pinia 实例并注册
const pinia = createPinia()
app.use(pinia)

// 注册 Vuex（如果你同时用 Vuex 和 Pinia）
app.use(store)

// 注册路由
app.use(router)

// 注册 ElementPlus 组件库
app.use(ElementPlus, { locale })

// 在挂载之前同步 token 和用户信息到 Pinia store
const userStore = useUserStore()

const token = localStorage.getItem('token')
const userInfoStr = localStorage.getItem('userInfo')

if (token) {
    userStore.setToken(token)
}

if (userInfoStr) {
    try {
        const parsedUserInfo = JSON.parse(userInfoStr)
        userStore.setUserInfo(parsedUserInfo)
    } catch (error) {
        console.error('Failed to parse userInfo from localStorage:', error)
    }
}


app.mount('#app')
